#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <errno.h>
#define MAX_CLIENTS 5
#define BUFFER_SIZE 1024
#define PORT 8080
int main()
{
    // Create a socket
    int lfd, cfd, ret, count = 0, i, j;
    struct sockaddr_in server_addr, client_addr;
    char buffer[BUFFER_SIZE];

    lfd = socket(AF_INET, SOCK_STREAM, 0);
    if (lfd < 0)
    {
        perror("server socket error");
        exit(1);
    }

    // 绑定端口和地址
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(PORT);
    server_addr.sin_addr.s_addr = INADDR_ANY;

    ret = bind(lfd, (struct sockaddr *)&server_addr, sizeof(server_addr));
    if (ret < 0)
    {
        perror("bind error");
        exit(1);
    }

    // 设置监听数量
    ret = listen(lfd, MAX_CLIENTS);
    if (ret < 0)
    {
        perror("listen error");
        exit(1);
    }

    // 接收客户端连接
    int socklen = sizeof(client_addr);
    cfd = accept(lfd, (struct sockaddr *)&client_addr, &socklen);
    if (cfd < 0)
    {
        perror("accept error");
        exit(1);
    }

    // 接收客户端数据
    for (i = 0; i < 10; i++)
    {
        count = read(cfd, buffer, BUFFER_SIZE);
        printf("client: %s\n", buffer);
        // 将数据转成大写,再发回去
        for (j = 0; j < count; j++)
        {
            buffer[j] = toupper(buffer[j]);
        }
        write(cfd, buffer, count);
        // 清空缓冲区
        memset(buffer, 0, BUFFER_SIZE);
    }

    // 关闭文件描述符
    close(cfd);
    close(lfd);

    return 0;
}